<template>
	<view class="index">
		<view class="equipment">
			<image src="../../static/c1.png" mode=""></image>
		</view>

		<Loading v-if="isOpenLoading" :loadingText="loadingText" />
		<view class="content">
			<ul>
				<li @click="handleClick1"><span>实时数据</span></li>
				<li @click="handleClick2"><span>配置参数</span></li>
				<li @click="handleClick3"><span>遥控输出</span></li>
				<li @click="handleClick4"><span>历史记录</span></li>
				<li @click="handleClick5"><span>产品信息</span></li>
				<li @click="handleClick6"><span>产品服务</span></li>
			</ul>
		</view>
		<view class="bottom">
			<!-- 状态变为断开或点击时重新尝试连接后台 -->
			<p @click="handleReconnection">状态：{{state?'已连接':'已断开'}}</p>
		</view>
	</view>
</template>
<script>
	import Loading from '../component/Loading.vue'
	export default {
		components: {
			Loading
		},
		data() {
			return {
				state: false,
				socketTask: null,
				isOpenLoading: true,
				loadingText: '加载中...',
				answer:'加载成功！'
			}
		},

		onLoad(options) {
			// this.jishi('连接中...','连接失败！')
			// 蓝牙
			this.checkBluetoothPermission();
			// options 是一个对象，包含了从调用页面传递过来的所有参数
			console.log(options);
			// 心跳机制
			this.initWebSocket();
			// this.checkWebSocketConnection(5000);

		},
		onUnload() {
			if (this.socketTask) {
				this.socketTask.close();
				// clearInterval(timer)
			}
		},


		methods: {
			// 蓝牙-------------------
			checkBluetoothPermission: function() {
				var that = this;
				uni.openBluetoothAdapter({
					success: function(res) {
						// 蓝牙适配器已打开，可以继续进行蓝牙操作
						console.log('蓝牙适配器已打开');
					},
					fail: function(err) {
						// 蓝牙适配器打开失败，可以在这里处理错误
						console.log('蓝牙适配器打开失败，错误码：' + err.errCode + '，错误信息：' + err.errMsg);
						// 如果用户拒绝了授权，可以显示一个按钮让用户手动开启权限
						if (err.errMsg === "openBluetoothAdapter:fail auth deny") { // 10001 表示用户拒绝授权
							that.showPermissionButton();
						}
					}
				});
			},

			showPermissionButton: function() {
				var that = this;
				uni.showModal({
					title: '提示',
					content: '蓝牙功能需要您的授权才能使用，是否去设置中授权？',
					confirmText: '去授权',
					cancelText: '取消',
					success: function(res) {
						if (res.confirm) {
							// 用户点击了去授权，打开设置页面
							uni.openSetting({
								success: function(res) {
									// 用户在设置页面做出选择后，返回到小程序
									if (res.authSetting['scope.bluetooth']) {
										// 用户开启了蓝牙权限，可以尝试再次调用 uni.openBluetoothAdapter
										that.checkBluetoothPermission();
									} else {
										// 用户没有开启蓝牙权限，可以给出相应的提示
										console.log('用户没有开启蓝牙权限');
									}
								}
							});
						} else if (res.cancel) {
							// 用户点击了取消，可以给出相应的提示
							console.log('用户取消了授权');
						}
					}
				});
			},
			// ------------------------
			// 当
			jishi() {
				// this.loadingText = text;
				// this.isOpenLoading = true
				if (this.isOpenLoading) {
					setTimeout(() => {
						this.loadingText = this.answer
					}, 10);
					setTimeout(() => {
						this.isOpenLoading = false;
						this.loadingText='加载中...'
					}, 1000)
				}
			},
			// socket-------------------
			// 当状态变为断开或点击时重新尝试连接后台-----------
			handleReconnection() {
				// 尝试重新连接
				this.socketTask.close();
				this.initWebSocket();
				// this.jishi()
			},
			// 初始化WebSocket连接
			initWebSocket() {
				this.isOpenLoading=true
				console.log("webscoket");
				this.socketTask = uni.connectSocket({
					url: 'ws://localhost:8080/',
					success: () => {
						console.log('WebSocket连接成功');

						this.startHeartbeat();
					},
					fail: (error) => {
						console.error('WebSocket连接失败', error);
					}
				});

				this.socketTask.onOpen((res) => {
					console.log('WebSocket 已打开', res);
				});

				this.socketTask.onMessage((res) => {
					this.state = true
					this.isOpenLoading = false
					console.log('收到服务器内容：' + res.data);
					this.answer='加载成功！！'
					this.jishi()

				});

				this.socketTask.onError((error) => {
					console.error('WebSocket 错误', error);
				});

				this.socketTask.onClose((res) => {
					console.log('WebSocket 已关闭', res);
					// this.checkWebSocketConnection(5000);
					this.state = false
					this.answer='加载失败！'
					this.jishi()
				});
			},

			// 发送心跳
			sendHeartbeat() {
				if (this.socketTask && this.socketTask.readyState === 1) {
					this.socketTask.send({
						data: JSON.stringify({
							type: '数据'
						})
					});
				}
			},

			// 开始心跳
			startHeartbeat() {
				setInterval(() => {
					this.sendHeartbeat();
				}, 2000); // 每5秒发送一次心跳
			},

			checkWebSocketConnection(interval) {
				setInterval(() => {
					console.log(`我正在每隔${interval/1000}s检查是否连接`);
					if (!this.state) {
						console.log('尝试重新连接WebSocket');
						// 尝试重新连接
						this.initWebSocket();
					}
				}, interval); // 每interval秒检查一次连接状态
			},

			// ----------------------

			// 实时数据
			handleClick1() {
				console.log("实时数据");
				uni.navigateTo({
					// 
					url: '../liveData/liveData?name=实时数据'
				})
			},
			handleClick2() {
				console.log("配置参数");
				uni.navigateTo({
					// 
					url: '../setParameter/setParameter?name=配置参数'
				})
			},
			handleClick3() {
				console.log("遥控输出");
				uni.navigateTo({
					// 
					url: '../telecontrol/telecontrol?name=遥控输出'
				})
			},
			handleClick4() {
				console.log("历史记录");
				uni.navigateTo({
					// 
					url: '../historicalData/historicalData?name=历史记录'
				})
			},
			handleClick5() {
				console.log("产品信息");
				uni.navigateTo({
					// 
					url: '../productInformation/productInformation?name=产品信息'
				})
			},
			handleClick6() {
				console.log("产品服务");
				uni.navigateTo({
					// 
					url: '../productService/productService?name=产品服务'
				})
			},

		}
	}
</script>

<style scoped lang="scss">
	/deep/ .u-loading-icon {
		position: absolute;
		top: 0;
		bottom: 0;
		right: 0;
		left: 0;
		margin: auto;
	}

	* {
		margin: 0;
		padding: 0;
	}

	.index {
		.equipment {
			display: flex;
			justify-content: center;
			height: 40vh;
			align-items: center;

			image {
				width: 300rpx;
				height: 300rpx;
				display: block;
			}
		}

		.content {
			height: 52vh;
			position: relative;
			overflow: hidden;

			ul {
				margin: auto;
				margin-top: 100rpx;
				box-sizing: border-box;
				width: 60%;
				display: flex;
				justify-content: center;
				flex-wrap: wrap;

				li {
					color: #6e5f4a;
					position: relative;
					padding: 20rpx;
					margin: 25rpx;
					background-color: #f0851b;
					border-radius: 10rpx;
				}

				//伪元素
				li::after {
					content: "";
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					// background: url('../../static/images/btnbg.png') no-repeat center;
					// background-size: 90% 90%;
					// opacity: 0.5; /* 只影响背景图片的透明度 */
					// pointer-events: none; /* 防止伪元素影响交互 *
				}

			}

		}

		.bottom {
			display: flex;
			justify-content: center;
			font-size: 24rpx;
			color: black;
		}
	}
</style>